package com.hancher.plugins.hrasmlog;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AdviceAdapter;

public class HrAsmLogClassVisitor extends ClassVisitor {

    private String className = null;

    public HrAsmLogClassVisitor(int api, ClassVisitor classVisitor) {
        super(api, classVisitor);
    }

    @Override
    public void visit(int version, int access, String className, String signature, String superName, String[] interfaces) {
        super.visit(version, access, className, signature, superName, interfaces);
        this.className = className;
    }

    @Override
    public MethodVisitor visitMethod(int methodAccess, String methodName, String methodDescriptor, String signature, String[] exceptions) {
        MethodVisitor methodVisitor = super.visitMethod(methodAccess, methodName, methodDescriptor, signature, exceptions);
        if ("onClick".equals(methodName) && "(Landroid/view/View;)V".equals(methodDescriptor)) {
            System.out.println("========HrAsmLogClassVisitor==========visitMethod className = " + className + ", methodName=" + methodName + ", methodDescriptor=" + methodDescriptor);
            return new AdviceAdapter(api, methodVisitor, methodAccess, methodName, methodDescriptor) {
                @Override
                public void visitCode() {
                    mv.visitVarInsn(Opcodes.ALOAD, 1);
                    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/hancher/plugins/hrasmlog/LogUtil", "click", "(Landroid/view/View;)V", false);
                    super.visitCode();
                }
            };
        } else if (methodName.startsWith("lambda$") && "(Landroid/view/View;)V".equals(methodDescriptor)) {
            System.out.println("========HrAsmLogClassVisitor==========visitMethod className = " + className + ", methodName=" + methodName + ", methodDescriptor=" + methodDescriptor);
            return new AdviceAdapter(api, methodVisitor, methodAccess, methodName, methodDescriptor) {
                @Override
                public void visitCode() {
                    mv.visitVarInsn(Opcodes.ALOAD, 0);
                    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/hancher/plugins/hrasmlog/LogUtil", "click", "(Landroid/view/View;)V", false);
                    super.visitCode();
                }
            };
        }
        return methodVisitor;
    }
}
